<template>
  <div class="users-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>用户管理</h1>
      <p>管理系统中的所有用户信息，包括普通用户和VIP用户</p>
    </div>

    <!-- 搜索工具栏 -->
    <div class="toolbar">
      <el-form :model="searchForm" class="search-form" inline>
        <el-form-item label="用户ID">
          <el-input v-model="searchForm.userId" placeholder="请输入用户ID" clearable />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="searchForm.nickname" placeholder="请输入昵称" clearable />
        </el-form-item>
        <el-form-item label="VIP状态">
          <el-select v-model="searchForm.vipStatus" placeholder="请选择VIP状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="VIP用户" value="1" />
            <el-option label="普通用户" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="toolbar-actions">
        <el-dropdown @command="handleExportCommand">
          <el-button type="success">
            <el-icon><Download /></el-icon>
            导出数据 <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="current">导出当前页</el-dropdown-item>
              <el-dropdown-item command="all">导出全部数据</el-dropdown-item>
              <el-dropdown-item command="selected" :disabled="selectedUsers.length === 0">
                导出选中数据 ({{ selectedUsers.length }})
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button type="primary" @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 批量操作工具栏 -->
    <div v-if="selectedUsers.length > 0" class="batch-toolbar">
      <div class="batch-info">
        <span>已选择 {{ selectedUsers.length }} 个用户</span>
        <el-button type="text" @click="handleClearSelection">取消选择</el-button>
      </div>
      <div class="batch-actions">
        <el-button type="danger" size="small" @click="handleBatchAction('disable')">
          <el-icon><Lock /></el-icon>
          批量禁用
        </el-button>
        <el-button type="success" size="small" @click="handleBatchAction('enable')">
          <el-icon><Unlock /></el-icon>
          批量启用
        </el-button>
        <el-button type="primary" size="small" @click="handleBatchAction('vip')">
          <el-icon><User /></el-icon>
          批量设VIP
        </el-button>
        <el-button type="warning" size="small" @click="handleBatchAction('credits')">
          <el-icon><Coin /></el-icon>
          批量加积分
        </el-button>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="content-card">
      <el-table
        :data="userList"
        :loading="loading"
        stripe
        style="width: 100%"
        @sort-change="handleSortChange"
        @selection-change="handleSelectionChange"
        ref="userTable"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="用户ID" width="80" sortable="custom" />
        <el-table-column prop="avatar" label="头像" width="80">
          <template #default="scope">
            <el-avatar :size="40" :src="scope.row.avatar" />
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="昵称" width="120" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="credits" label="积分余额" width="100" sortable="custom">
          <template #default="scope">
            <span class="credits-amount">{{ formatNumber(scope.row.credits || 0) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isVip" label="VIP状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isVip ? 'warning' : 'info'">
              {{ scope.row.isVip ? 'VIP用户' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="vipExpireTime" label="VIP到期时间" width="180">
          <template #default="scope">
            <span v-if="scope.row.vipExpireTime">
              {{ formatDate(scope.row.vipExpireTime) }}
            </span>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="registerTime" label="注册时间" width="180" sortable="custom">
          <template #default="scope">
            {{ formatDate(scope.row.registerTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleViewUser(scope.row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button size="small" type="warning" @click="handleEditCredits(scope.row)">
              <el-icon><EditPen /></el-icon>
              积分
            </el-button>
            <el-dropdown @command="(cmd: string) => handleUserAction(cmd, scope.row)">
              <el-button size="small" type="info">
                更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="setVip">设为VIP</el-dropdown-item>
                  <el-dropdown-item command="removeVip">取消VIP</el-dropdown-item>
                  <el-dropdown-item command="ban" divided>封禁用户</el-dropdown-item>
                  <el-dropdown-item command="unban">解封用户</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </div>

    <!-- 用户详情弹窗 -->
    <el-dialog v-model="userDetailVisible" title="用户详情" width="600px">
      <el-descriptions v-if="currentUser" :column="2" border>
        <el-descriptions-item label="用户ID">{{ currentUser.id }}</el-descriptions-item>
        <el-descriptions-item label="昵称">{{ currentUser.nickname }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ currentUser.phone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="积分余额">{{ formatNumber(currentUser.credits || 0) }}</el-descriptions-item>
        <el-descriptions-item label="累计获得积分">{{ formatNumber(currentUser.totalCreditsEarned || 0) }}</el-descriptions-item>
        <el-descriptions-item label="累计消费积分">{{ formatNumber(currentUser.totalCreditsConsumed || 0) }}</el-descriptions-item>
        <el-descriptions-item label="VIP状态">
          <el-tag :type="currentUser.isVip ? 'warning' : 'info'">
            {{ currentUser.isVip ? 'VIP用户' : '普通用户' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="VIP到期时间">
          {{ currentUser.vipExpireTime ? formatDate(currentUser.vipExpireTime) : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="注册时间">{{ formatDate(currentUser.registerTime) }}</el-descriptions-item>
        <el-descriptions-item label="最后登录">{{ formatDate(currentUser.lastLoginTime) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 积分管理弹窗 -->
    <el-dialog v-model="creditsEditVisible" title="积分管理" width="400px">
      <el-form :model="creditsForm" :rules="creditsRules" ref="creditsFormRef" label-width="80px">
        <el-form-item label="当前积分">
          <span class="credits-current">{{ formatNumber(currentUser?.credits || 0) }}</span>
        </el-form-item>
        <el-form-item label="操作类型" prop="type">
          <el-radio-group v-model="creditsForm.type">
            <el-radio value="add">增加积分</el-radio>
            <el-radio value="subtract">扣减积分</el-radio>
            <el-radio value="set">设置积分</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="积分数量" prop="amount">
          <el-input-number v-model="creditsForm.amount" :min="0" :max="999999" controls-position="right" />
        </el-form-item>
        <el-form-item label="操作原因" prop="reason">
          <el-input v-model="creditsForm.reason" type="textarea" placeholder="请输入操作原因" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="creditsEditVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmCredits" :loading="creditsSubmitting">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { getUserList, getUserDetail, updateUserCredits } from '@/api'

// 响应式数据
const loading = ref(false)
const userList = ref<any[]>([])
const selectedUsers = ref<any[]>([])
const userDetailVisible = ref(false)
const creditsEditVisible = ref(false)
const creditsSubmitting = ref(false)
const currentUser = ref<any>(null)
const creditsFormRef = ref<FormInstance>()
const userTable = ref()

// 搜索表单
const searchForm = reactive({
  userId: '',
  nickname: '',
  vipStatus: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 积分编辑表单
const creditsForm = reactive({
  type: 'add',
  amount: 0,
  reason: ''
})

// 积分表单验证规则
const creditsRules = {
  type: [{ required: true, message: '请选择操作类型', trigger: 'change' }],
  amount: [{ required: true, message: '请输入积分数量', trigger: 'blur' }],
  reason: [{ required: true, message: '请输入操作原因', trigger: 'blur' }]
}

// 加载用户列表
const loadUserList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.page,
      size: pagination.size,
      userId: searchForm.userId,
      nickname: searchForm.nickname,
      vipStatus: searchForm.vipStatus
    }
    
    const response = await getUserList(params)
    
    if (response && response.success) {
      userList.value = response.data.data || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error('加载用户列表失败')
      console.error('API response:', response)
    }
  } catch (error) {
    ElMessage.error('加载用户列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadUserList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    (searchForm as any)[key] = ''
  })
  pagination.page = 1
  loadUserList()
}

// 导出数据
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 刷新
const handleRefresh = () => {
  loadUserList()
}

// 查看用户详情
const handleViewUser = (user: any) => {
  currentUser.value = user
  userDetailVisible.value = true
}

// 编辑积分
const handleEditCredits = (user: any) => {
  currentUser.value = user
  creditsForm.type = 'add'
  creditsForm.amount = 0
  creditsForm.reason = ''
  creditsEditVisible.value = true
}

// 确认积分操作
const handleConfirmCredits = async () => {
  if (!creditsFormRef.value || !currentUser.value) return
  
  try {
    await creditsFormRef.value.validate()
    
    creditsSubmitting.value = true
    
    // 调用真实API
    const response = await updateUserCredits(currentUser.value.id, {
      type: creditsForm.type,
      amount: creditsForm.amount,
      reason: creditsForm.reason
    })
    
    if (response && response.success) {
      ElMessage.success('积分操作成功')
      creditsEditVisible.value = false
      loadUserList()
    } else {
      ElMessage.error(response?.message || '积分操作失败')
    }
  } catch (error) {
    ElMessage.error('积分操作失败')
    console.error(error)
  } finally {
    creditsSubmitting.value = false
  }
}

// 用户操作
const handleUserAction = async (command: string, user: any) => {
  const actions: Record<string, { text: string; type: 'warning' | 'info' }> = {
    setVip: { text: '设为VIP', type: 'warning' },
    removeVip: { text: '取消VIP', type: 'warning' },
    ban: { text: '封禁用户', type: 'warning' },
    unban: { text: '解封用户', type: 'info' }
  }
  
  const action = actions[command]
  if (!action) return
  
  try {
    await ElMessageBox.confirm(`确定要${action.text}吗？`, '确认操作', {
      type: action.type
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success(`${action.text}成功`)
    loadUserList()
  } catch (error) {
    // 用户取消操作
  }
}

// 排序改变
const handleSortChange = ({ prop, order }: any) => {
  console.log('Sort change:', prop, order)
  loadUserList()
}

// 每页数量改变
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadUserList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadUserList()
}

// 格式化数字
const formatNumber = (num: number) => {
  return num.toLocaleString()
}

// 格式化日期
const formatDate = (date: Date | string) => {
  if (!date) return '-'
  const d = new Date(date)
  return d.toLocaleString('zh-CN')
}

// 获取状态类型
const getStatusType = (status: string) => {
  return status === 'active' ? 'success' : 'danger'
}

// 获取状态文本
const getStatusText = (status: string) => {
  return status === 'active' ? '正常' : '封禁'
}

// 批量选择处理
const handleSelectionChange = (selection: any[]) => {
  selectedUsers.value = selection
}

// 清除选择
const handleClearSelection = () => {
  userTable.value.clearSelection()
}

// 数据导出处理
const handleExportCommand = async (command: string) => {
  let dataToExport: any[] = []
  let filename = ''
  
  switch (command) {
    case 'current':
      dataToExport = userList.value
      filename = `用户数据_当前页_${new Date().getTime()}`
      break
    case 'all':
      try {
        const response = await getUserList({ current: 1, size: 999999 })
        dataToExport = response.data.data || []
        filename = `用户数据_全部_${new Date().getTime()}`
      } catch (error) {
        ElMessage.error('获取全部数据失败')
        return
      }
      break
    case 'selected':
      dataToExport = selectedUsers.value
      filename = `用户数据_选中_${new Date().getTime()}`
      break
    default:
      return
  }
  
  if (dataToExport.length === 0) {
    ElMessage.warning('没有数据可导出')
    return
  }
  
  // 使用简单的CSV导出
  exportToCSV(dataToExport, filename)
  ElMessage.success(`成功导出 ${dataToExport.length} 条数据`)
}

// CSV导出函数
const exportToCSV = (data: any[], filename: string) => {
  const headers = ['用户ID', '昵称', '手机号', '积分余额', 'VIP状态', '状态', '注册时间']
  const csvContent = [
    headers.join(','),
    ...data.map(user => [
      user.id,
      user.nickname || '',
      user.phone || '',
      user.credits || 0,
      user.vipLevel > 0 ? 'VIP' : '普通',
      getStatusText(user.status),
      formatDate(user.createTime)
    ].join(','))
  ].join('\n')
  
  const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = filename + '.csv'
  link.click()
}

// 批量操作处理
const handleBatchAction = async (action: string) => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请先选择用户')
    return
  }
  
  const actionMap: Record<string, { text: string; type: 'warning' | 'info' }> = {
    disable: { text: '禁用', type: 'warning' },
    enable: { text: '启用', type: 'info' },
    vip: { text: '设为VIP', type: 'warning' },
    credits: { text: '批量加积分', type: 'info' }
  }
  
  const actionInfo = actionMap[action]
  if (!actionInfo) return
  
  try {
    if (action === 'credits') {
      // 批量加积分需要输入数量
      const { value } = await ElMessageBox.prompt('请输入要增加的积分数量', '批量加积分', {
        inputType: 'number',
        inputValue: '100',
        inputValidator: (value) => {
          const num = parseInt(value)
          if (isNaN(num) || num <= 0) {
            return '请输入有效的积分数量'
          }
          return true
        }
      })
      
      const credits = parseInt(value)
      await batchUpdateCredits(selectedUsers.value, credits)
      ElMessage.success(`成功为 ${selectedUsers.value.length} 个用户增加 ${credits} 积分`)
    } else {
      await ElMessageBox.confirm(
        `确定要对选中的 ${selectedUsers.value.length} 个用户执行${actionInfo.text}操作吗？`,
        '确认批量操作',
        { type: actionInfo.type }
      )
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000))
      ElMessage.success(`成功${actionInfo.text} ${selectedUsers.value.length} 个用户`)
    }
    
    handleClearSelection()
    loadUserList()
  } catch (error) {
    // 用户取消操作或发生错误
    if (error !== 'cancel') {
      ElMessage.error('批量操作失败')
    }
  }
}

// 批量更新积分
const batchUpdateCredits = async (users: any[], credits: number) => {
  const promises = users.map(user => 
    updateUserCredits(user.id, {
      type: 'add',
      amount: credits,
      reason: '管理员批量操作'
    })
  )
  
  await Promise.all(promises)
}

// 页面加载
onMounted(() => {
  loadUserList()
})
</script>

<style scoped>
.users-management {
  padding: 0;
}

.pagination {
  margin-top: 20px;
  justify-content: center;
}

.credits-amount {
  font-weight: 600;
  color: #f56c6c;
}

.credits-current {
  font-size: 16px;
  font-weight: 600;
  color: #f56c6c;
}

.text-muted {
  color: #909399;
}

.dialog-footer {
  text-align: right;
}

/* 批量操作工具栏样式 */
.batch-toolbar {
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 12px 16px;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  animation: slideDown 0.3s ease;
}

.batch-info {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #606266;
  font-size: 14px;
}

.batch-actions {
  display: flex;
  gap: 8px;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 16px;
  }
  
  .search-form {
    width: 100%;
  }
}
</style>
